利用回溯法求解迷宫问题大致可以这样理解:
1.确定迷宫大小,确定迷宫格可走阻塞已走过的标志,确定入口出口;
2.想清楚如何走,如何找到出口(走到每一个格子都考虑其上下左右相邻能否走通,根据格子状态判断)
3.在找到下一步走的一个方向后,就去执行;其他可走路线等回溯后验证;
4.在四个方向都验证不通后,就会回溯到上一个格子,验证下一个方向的可行性。
5.在走到的单元格坐标和出口相同后,即可输出所保存路径;
6.再回溯寻找下一个解;
7,直到验证所有解。
//实现迷宫解运用回溯法的代码如下:
#include<iostream>
#include"conio.h"using namespace std;
#define MAX_H 80
#define MAX_W 50
//迷宫格状态有阻塞(block),空白(empty),经过(pass)三种状态。
typedef enum
{
Block,
Empty,
Pass
}MazeCellStatus;
//迷宫单元格坐标,定义到结构体中
typedef struct
{
int x;
int y;
}CellCoor;
//迷宫走过路径的路径保存记录,定义为一个结构体
typedef struct
{
CellCoor way[MAX_H * MAX_W];
int Distance;
}WayRecord;
//对迷宫未探索前状态描述
MazeCellStatus maze[MAX_H][MAX_W]={
{Empty,Block,Block,Block,Block,Block,Block,Block,Block,Block},
{Empty,Block,Empty,Empty,Block,Empty,Empty,Empty,Block,Block},
{Empty,Empty,Empty,Block,Block,Empty,Block,Empty,Empty,Block},
{Empty,Block,Block,Empty,Empty,Empty,Block,Block,Empty,Block},
{Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Empty,Block},
{Empty,Block,Block,Block,Block,Block,Block,Block,Empty,Empty},
};
void OutputSolution(WayRecord MWR);
void TryMazeSolution(int MazeHigh,int MazeWeight,CellCoor entry,CellCoor exit,WayRecord MWR);
//寻找迷宫答案的函数体
void MazeSolution(int MazeHigh,int MazeWeight,CellCoor entry,CellCoor exit)
{
WayRecord MWR;
MWR.Distance = 0;
MWR.way[MWR.Distance].x = entry.x;
MWR.way[MWR.Distance].y = entry.y;
MWR.Distance++;
TryMazeSolution( MazeHigh,MazeWeight,entry,exit,MWR);
}
//寻找迷宫答案(回溯法)的可能解
void TryMazeSolution(int MazeHigh,int MazeWeight,CellCoor cur,CellCoor exit,WayRecord MWR)
{
int xshift[4]={0,0,-1,1}; //相邻位置相对于当前位置x的坐标
int yshift[4]={-1,1,0,0}; //相邻位置相对于当前位置y的坐标
CellCoor adjCell; //当前位置的相邻位置
if(cur.x==exit.x && cur.y==exit.y)
{ //已达到出口,输出解
OutputSolution(MWR);
}
else
{
for(int i=0;i<4;i++)
{
adjCell.x=cur.x + xshift[i]; //求相邻位置的x坐标
adjCell.y=cur.y + yshift[i]; //求相邻位置的y坐标
if(adjCell.x>=0&&adjCell.x<=MazeWeight && adjCell.y>=0&&adjCell.y<=MazeHigh && (maze[adjCell.y][adjCell.x]==Empty))
{
//相邻位置在迷宫内并且为空白,将相邻位置存于路径中
MWR.way[MWR.Distance].x = adjCell.x;
MWR.way[MWR.Distance].y = adjCell.y;
MWR.Distance++;
maze[adjCell.y][adjCell.x] = Pass;
TryMazeSolution(MazeHigh,MazeWeight,adjCell,exit,MWR); //对相邻位置进行递归
MWR.Distance--; //从路径中去掉adjCell,路径长度将自减1
maze[adjCell.y][adjCell.x] = Empty;
}
}
}
}
void OutputSolution(WayRecord MWR)
{
static int num=0;
int i;
printf("第%d条路径:",++num); //num表示当前以求的解得个数
for(i=0;i<MWR.Distance;i++)
{
printf("(%d,%d) ",MWR.way[i].x,MWR.way[i].y);
}
printf("\n");
getch();
}
void main()
{
int MazeHigh = 6;
int MazeWeight = 10;
CellCoor entry = {0,0};
CellCoor exit = {9,5};
MazeSolution(MazeHigh,MazeWeight,entry,exit);
getch();
}